package com.tian.excel.service.impl;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.tian.excel.entity.Order;
import com.tian.excel.mapper.OrderMapper;
import com.tian.excel.service.OrderService;
import com.tian.excel.utils.HttpClient;
import com.tian.excel.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Tian
 * @version: 1.0
 * @since: 1.0
 * @date: 2024/8/2/15:59
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    Config config;

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.mch_id}")
    private String mchId;

    @Value("${weixin.api_key}")
    private String apiKey;

    //获取微信支付订单信息
    @Override
    public R createNative(String orderNo) {
        //根据订单号查询订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        queryWrapper.eq("status",0);
        Order order = orderMapper.selectOne(queryWrapper);
        System.out.println("===========order===================");
        System.out.println(order);
        System.out.println("==================================");
        if (order != null){
            try {
                //设置请求的参数------格式：xml
                Map<String, String> params=new HashMap<>();
                params.put("appid",appId);
                params.put("mch_id",mchId);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body",order.getCourseTitle());
                params.put("out_trade_no",orderNo);
                params.put("total_fee",order.getTotalFee().multiply(new BigDecimal(100)).longValue()+"");
                params.put("spbill_create_ip","127.0.0.1");
                params.put("notify_url","http://localhost:8080/pay/back");
                params.put("trade_type","NATIVE");
                //创建HttpClient对象,作为远程调用
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //支持https协议
                httpClient.setHttps(true);
                //设置请求参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
                //执行请求
                httpClient.post();
                //获取返回结果
                String xml = httpClient.getContent();
                System.out.println(xml);
                Map<String, String> stringMap = WXPayUtil.xmlToMap(xml);
                if(stringMap.get("result_code").equals("SUCCESS")){
                    HashMap<Object, Object> result = new HashMap<>();
                    result.put("codeUrl",stringMap.get("code_url"));
                    result.put("price",order.getTotalFee());
                    result.put("orderNo",orderNo);
                    return new R(200,"成功生成二维码",result);

                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return new R(500,"支付失败",null);
    }

    //查询微信支付订单的状态
    @Override
    public R queryWeiXinPayStatus(String orderNo) {
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            HashMap<String, String> params = new HashMap<>();
            params.put("appid",appId);
            params.put("mch_id",mchId);
            params.put("out_trade_no",orderNo);
            params.put("nonce_str",WXPayUtil.generateNonceStr());
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
            httpClient.post();
            String xml = httpClient.getContent();
            System.out.println(xml);
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if(map.get("trade_state").equals("SUCCESS")){
                   return updateOrderStatus(orderNo,0);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return new R(400,"订单未支付",null);
    }

    //支付宝使用easy版生成支付二维码
    @Override
    public R zhiFuBaoEasyPay(String orderNo)  {
        try {
            Factory.setOptions(config);
            //调用支付宝接口
            AlipayTradePrecreateResponse re = Factory.Payment.FaceToFace().preCreate("iphone15 promax 17", orderNo, "12999");
            String httpBody = re.getHttpBody();
            System.out.println("===============支付宝支付信息======================");
            System.out.println(httpBody);
            System.out.println("===================================");
            JSONObject entries = JSONUtil.parseObj(httpBody);
            System.out.println(entries);
            System.out.println();
            JSONObject a = (JSONObject) entries.get("alipay_trade_precreate_response");
            Object qr_code = a.get("qr_code");
            if(qr_code!=null) {
                String qrUrl = qr_code.toString();
                //String qrUrl = entries.get("alipay_trade_precreate_response").toString()+entries.get("qr_code").toString();
                System.out.println("==============支付宝二维码===================");
                System.out.println(qrUrl);
                System.out.println("============================");
                return new R(200, "生成二维码成功", qrUrl);
            }
            if(a.get("code")!=null){
                return new R(500,"订单已支付,请勿重复操作",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new R(500,"二维码生成失败",null);
    }


    //查询使用支付宝支付的订单的状态
    @Override
    public R queryZFBPayStatus(String orderNo) {

        try {
            Factory.setOptions(config);
            AlipayTradeQueryResponse query = Factory.Payment.Common().query(orderNo);
            String httpBody = query.getHttpBody();
            JSONObject entries = JSONUtil.parseObj(httpBody);
            System.out.println("===========支付宝订单支付状态=======================");
            System.out.println(entries);
            JSONObject re = (JSONObject) entries.get("alipay_trade_query_response");

            if(re.get("code").equals("10000")&&!re.get("buyer_pay_amount").equals("0.00")){
                return updateOrderStatus(orderNo, 1);
            }
            //return new R(400,"订单支付失败",null);

        } catch (Exception e) {
            e.printStackTrace();
        }
         return new R(400,"订单未支付",null);
    }






    //修改订单信息
    public R updateOrderStatus(String orderNo,int payType){
        //修改订单状态
        Order order = new Order();
        order.setStatus(1);
        order.setPayType(payType);
        order.setGmtModified(new Date());
        QueryWrapper<Order> wrapper= new QueryWrapper<Order>();
        wrapper.eq("order_no",orderNo);
        wrapper.eq("status",0);

        int i = orderMapper.update(order, wrapper);
        if(i>0){
            return new R(200,"支付成功",null);
        }
        return new R(500,"支付失败",null);
    }


}
